package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.ttl.threadpool.TtlExecutors;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Wangbj
 * @date 2024年04月22日 22:00
 */

@Slf4j
@Service
public class LoginUserSetUtil {

    @Resource
    TokenService tokenService;

    private static final ConcurrentHashMap<String, Field> FIELD_CACHE = new ConcurrentHashMap<>();


    /**
     * 自动复制个人信息
     *
     * @param entity
     * @param type
     */
    public void populateFields(Object entity, int type) {

        LoginUser loginUser = tokenService.getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            return;
        }
        Class<?> entityClass = entity.getClass();
        if (type == 1) {
            setFieldIfExist(entity, entityClass, "createUserId", loginUser.getUserid());
            setFieldIfExist(entity, entityClass, "createUserName", loginUser.getSysUser().getNickName());
            setFieldIfExist(entity, entityClass, "organizationId", loginUser.getOrganizationId());
            setFieldIfExist(entity, entityClass, "contestId", loginUser.getContestId());

        }
        setFieldIfExist(entity, entityClass, "updateUserId", loginUser.getUserid());
        setFieldIfExist(entity, entityClass, "updateUserName", loginUser.getSysUser().getNickName());
        setFieldIfExist(entity, entityClass.getSuperclass(), "updateTime", DateUtil.date());
    }


    private static void setFieldIfExist(Object entity,Class<?> entityClass, String fieldName, Object value) {
        Field field = getField(entityClass, fieldName);
        if (field != null) {
            try {
                field.setAccessible(true);
                field.set(entity, value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Unexpected IllegalAccessException while accessing field " + fieldName, e);
            }
        }
    }

    private static Field getField(Class<?> clazz, String fieldName) {
        Field field = FIELD_CACHE.get(clazz.getName() + "#" + fieldName);
        if (field == null) {
            try {
                field = clazz.getDeclaredField(fieldName);
                FIELD_CACHE.put(clazz.getName() + "#" + fieldName, field);
            } catch (NoSuchFieldException ignored) {
                // Field does not exist, do nothing
            }
        }
        return field;
    }
    //测试数据
    //        LoginUser loginUser = new LoginUser();
//        loginUser.setUserid(100l);
//        SysUser sysUser = new SysUser();
//        sysUser.setUserName("wangbj");
//        sysUser.setNickName("wangbj");
//        loginUser.setSysUser(sysUser);
//        loginUser.setContestId(6l);
//        loginUser.setOrganizationId(1l);
}
